package com.chat.core.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chat.core.entity.ChatSession;
import com.chat.core.entity.ChatSessionRead;
import com.chat.core.entity.GroupChatRead;
import com.chat.core.entity.User;
import com.chat.core.service.ChatSessionReadService;
import com.chat.core.service.ChatSessionService;
import com.chat.core.service.GroupChatReadService;
import com.chat.core.service.UserService;
import com.chat.core.utils.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 系统接口
 */
@RestController
@RequestMapping("sys")
public class SystemController {

    @Resource
    private GroupChatReadService chatReadService;
    @Resource
    private UserService userService;
    @Resource
    private ChatSessionService sessionService;
    @Resource
    private ChatSessionReadService sessionReadService;

    private static final String fileUrl = "D://images/";

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        Assert.isTrue(!file.isEmpty(),"没有选中任何文件！");
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String fileName =  UUID.randomUUID().toString().replaceAll("-", "");
        File uploadFileSaveDir = new File(fileUrl);
        if (!uploadFileSaveDir.exists()){
            uploadFileSaveDir.mkdirs();
        }
        File dest = new File(fileUrl + fileName+ext);
        file.transferTo(dest);
        return Result.ok("上传成功！",fileName+ext);
    }

    /**
     * 发送群聊消息
     * @return
     */
    @PostMapping("sendGroup")
    public Result sendGroupMessage(@RequestBody GroupChatRead read) throws IOException {
        read.setSendDate(new DateTime());
        User user = userService.getById(read.getUserId());
        read.setUser(user);
        WsSessionManager.sendGroupMessage(read.getUserId(), JSONUtil.toJsonPrettyStr(read));
        boolean save = chatReadService.save(read);
        Assert.isTrue(save,"发送失败");
        return Result.ok("发送成功！");
    }

    @PostMapping("send")
    public Result sendMessage(@RequestBody ChatSession session) throws IOException {
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<>();
        wrapper.eq("CRT_USER_ID",session.getCrtUserId()).eq("USER_ID",session.getUserId()).or().
                eq("CRT_USER_ID",session.getUserId()).eq("USER_ID",session.getCrtUserId());
        ChatSession chatSession = sessionService.getOne(wrapper);
        ChatSessionRead read = new ChatSessionRead();
        read.setCrtDate(new DateTime());
        read.setCrtUserId(session.getCrtUserId());
        read.setChatSessionId(chatSession.getId());
        read.setContent(session.getMessage());
        if (WsSessionManager.isExist(session.getUserId())){
            read.setReadState(1);
        }else {
            read.setReadState(0);
        }
        boolean save = sessionReadService.save(read);
        Assert.isTrue(save,"发送失败");

        User user = userService.getById(session.getCrtUserId());
        read.setUser(user);
        WsSessionManager.sendMessage(session.getUserId(), JSONUtil.toJsonPrettyStr(read));
        return Result.ok("发送成功！");
    }
}
